package example.demo.customerclassloader;

import cn.hutool.core.io.FileUtil;
import sun.net.www.ParseUtil;

import java.io.File;
import java.security.SecureClassLoader;
import java.util.HashMap;
import java.util.Map;


public class RaoClassLoader extends ClassLoader {
    private final String classFilePath;
    //key是包名+类名 example.demo.Rao  value为对应的class文件
    private final Map<String, File> files;
    public RaoClassLoader(String classFilePath) {
        super(Thread.currentThread().getContextClassLoader());
        this.classFilePath = classFilePath;
        files = listFile(new File(classFilePath), new HashMap<>());
    }
    public Map<String, File> listFile(File file, Map<String, File> files) {
        if (file.isDirectory()) {
            for (File filesrc : file.listFiles()) {
                listFile(filesrc, files);
            }
        } else { //拼成包名+类名
            files.put("example.demo." + file.getName().replace(".class", ""), file);
            return files;
        }
        return files;
    }
    /**
     * <? 指定包名+类名 找到对应的class文件，进行class文件的加载
     * RaoClassLoader raoClassLoader = new RaoClassLoader(filePath);
     * Class<?> aClass = raoClassLoader.loadClass("example.demo.Rao");
     * System.out.println("aClass = " + aClass);  aClass = class example.demo.Rao
     * System.out.println("aClass.getClassLoader() = " + aClass.getClassLoader());  aClass.getClassLoader() = example.demo.customerclassloader.RaoClassLoader@2626b418
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        if (null != files.get(name)) {
            byte[] bytes = FileUtil.readBytes(files.get(name));
            //加载
            return this.defineClass(name, bytes, 0, bytes.length);
        } else {
            //没找到，就来这里
            return super.findClass(name);
        }
    }
}
